<?php
/**
 * 秒杀活动预约秒杀类 activitySpike
 * @package  htdocs
 * @subpackage  module/base/activity
 * @author   allen.qiang <allen.qiang@fistforward.com>
 * @version 1.0
 */

class activitySpike {
    public $billPromotion='358';//秒杀促销渠道ID //测试数据323 正式358
    public $eventsID = "MS";//活动编号
    public $eventsName="秒杀";//活动名称
    public $beginTime="2014-10-17 10:00:00";//活动开始时间
    public $endTime="2014-11-06 10:00:00";//活动结束时间
    public $billPromotion_xwc='360';//下午茶促销渠道ID //测试数据343   正式360
    public $billPromotion_lv5='373';//LV5会员五折购销渠道ID //测试数据359   正式373

    public $billPromotion_ny_xyk='374';//农业银行信用卡五折购促销渠道ID //测试数据363  正式 374   //allen.qiang 20141029 add
    public $payTypeID_ny_xyk=62; //农业银行信用卡在线支付payTypeID  //测试数据56  正式62    //allen.qiang 20141029 add
    public $paymentID_ny_xyk=64; //农业银行信用卡货到付款paymentID  //测试数据64   正式64    //allen.qiang 20141029 add
    //add by 20141105 allen.qiang FUN-AC-0013-销售BD双11活动 start
    public $paymentID_11_man=379;   //双11活动礼包神秘之约-男  正式 379
    public $paymentID_11_women=380; //双11活动礼包神秘之约-女  正式 380
    public $paymentID_11_pet=381;   //双11活动礼包神秘之约-宠物 正式 381
    public $paymentID_11_pc=382;    //双11活动礼包前台促销渠道ID 正式 382 测试374
    public $selector_11=347;        //双11活动礼包商品筛选器ID 正式 347 测试284
    public $selector_goods=348;    //双11活动礼包商品促销ID 正式 348  测试293
    //add by 20141105 allen.qiang FUN-AC-0013-销售BD双11活动 end
    /**
     * 查询秒杀活动参与人数详情
     * @param string $eventsID 活动编号
     * @return null|array
     */
    public function searchEventsDetail($eventsID) {
        global $G_SHOP;
        //查询分类信息
        $search_sql = "SELECT * FROM activity_events WHERE eventsID='".$eventsID."'";
        $temp_item_array = &$G_SHOP->DBCA->stmt_query($search_sql);
        if (!$temp_item_array)
            return null;

        $customer_array = array();

        foreach ($temp_item_array as &$item) {

            //用户信息数组
            $customer_array[]  = array(
                'uuid'	    => 	$item->uuid,
                'timeStamp'	=>	$item->timeStamp,
                'creator' 	=> 	$item->creator,
                'createTime' => $item->createTime,
                'eventsID'	=> 	$item->eventsID,
                'eventsName'	=> 	$item->eventsName,
                'beginTime'	=> 	$item->beginTime,
                'endTime'	=> 	$item->endTime,
                'sourceID'	=>	$item->sourceID,
                'number'		=> 	$item->number,
            );
        }
        if (!$customer_array) {
            return null;
        }

        return $customer_array[0];

    }

    /**
     * 查询秒杀活动参与人数详情
     * @return null|array
     */
    public function searchSpikeDetail() {
        global $G_SHOP;

        $pcustID=$G_SHOP->currentPCustID;
      //  $city_id =$G_SHOP->get_cookie_info('EBSIG_CITY_ID');

        $s_sql="SELECT * FROM `activity_goods` WHERE isDisable=0 ORDER BY orderID";
        $temp_array = &$G_SHOP->DBCA->stmt_query($s_sql);
        if (!$temp_array)
            return null;

        $customer_array = array();

        $i=1;
        foreach ($temp_array as &$items) {
            $search_sql = "SELECT COUNT(*) AS nuber FROM activity_spike WHERE spikeDate='".date('Y-m-d')."' AND sku='".$items->sku."' AND codeState<>0";
            $temp_item_array = &$G_SHOP->DBCA->stmt_query($search_sql);
            if (!$temp_item_array)
                return null;
            $class="Seckill un_Seckill";
            $date=date('Y/m/d 14:00:00');//测试数据
            if($i>1)
                $date=date('Y/m/d 15:00:00');//测试数据

            $isSipke="";
            $sipkDate=date('Y-m-d');
            if(date('Y-m-d H:i:s')>date('Y-m-d 15:59:59'))//测试数据
                $sipkDate=date('Y-m-d',strtotime('+1 day'));
            $activitySpike = new entity('activity_spike');
            $activitySpike->pcustID = $pcustID;
            $activitySpike->spikeDate =$sipkDate;
            if($G_SHOP->DBCA->fetch($activitySpike))
            {
                $isSipke="Y";
            }

            foreach ($temp_item_array as &$item) {
                $sum=99-$item->nuber*20;
                $btnName="秒杀价：99  立即秒杀";

                if($sum<0||date('Y-m-d H:i:s')>date('Y-m-d 15:59:59')){
                    $sum=0;
                    $btnName="抢光啦";
                    $class="Seckill un_Seckill";
                }
                //用户信息数组
                $customer_array[]  = array(
                    'product_id'	    => 	$i,
                    'nuber'	    => 	$sum,
                    'buttonName'	    => 	$btnName,
                    'product_code'   => 	$items->sku,
                    'product_src'   => 	$items->src,
                    'product_postID_SH'   => 	$items->postID_SH,
                    'product_postID_HZ'   => 	$items->postID_HZ,
                    'product_goodsName'   => 	$items->goodsName,
                    'product_pounds'   => 	$items->pounds,
                    'product_date'  =>$date,
                    'product_class' =>$class,
                    'product_spkie' =>$isSipke
                );
            }
            $i++;
        }
        return $customer_array;

    }

    /**
     * 保存/修改秒杀预约表信息
     * @param array $arg_array 参数数组
     * @return null|array
     */
    public function saveSpike( $arg_array )
    {
        global $G_SHOP;

        try {

            $G_SHOP->DBCA->beginTransaction();

            $activitySpike = new entity('activity_spike');
            $activitySpike->pcustID = $arg_array['pcustID'];

            $operFlg=$arg_array['operFlg'];
            if ($operFlg == 1) {//预约秒杀

                //查询秒杀预约信息
                $activitySpike->spikeDate =$arg_array['spikeDate'];
                if($G_SHOP->DBCA->fetch($activitySpike))
                {
                    $G_SHOP->DBCA->commit();
                    if($arg_array['spikeDate']==date("Y-m-d"))
                        return array( 'code' => 300, 'message' => '您已预约成功，今天15:00可秒杀' );
                    else
                        return array( 'code' => 300, 'message' => '您已预约成功，明天15:00可秒杀' );
                }

                $activitySpike->creator = $arg_array['creator'];
                $activitySpike->appointmentTime = $arg_array['appointmentTime'];
                $activitySpike->isSpike = $arg_array['isSpike'];

                //保存秒杀预约信息
                $G_SHOP->DBCA->save( $activitySpike ) ;

                //保存秒杀活动信息
                $number=1;
                $activityEvents=new entity('activity_events');
                $activityEvents->eventsID = $this->eventsID;

                if( !$G_SHOP->DBCA->fetch($activityEvents) ) {//新增

                    $activityEvents->eventsName =  $this->eventsName;
                    $activityEvents->beginTime =  $this->beginTime;
                    $activityEvents->endTime =  $this->endTime;
                    $activityEvents->sourceID = $this->billPromotion;
                    $activityEvents->number += $number;
                }else{
                    $activityEvents->number += $number;//修改参与人数
                }
                $G_SHOP->DBCA->save($activityEvents) ;
                $G_SHOP->DBCA->commit();
                if($arg_array['spikeDate']==date("Y-m-d"))
                    return array( 'code' => 200, 'message' => '预约成功，今天15:00可秒杀' );
                else
                    return array( 'code' => 200, 'message' => '预约成功，明天15:00可秒杀' );

            } else if($operFlg == 2){//立即秒杀

                $db_sql = "SELECT COUNT(*) AS nuber FROM activity_spike WHERE spikeDate='".date('Y-m-d')."' AND pcustID='".$arg_array['pcustID']."' AND codeState<>0 ";
                $temp_array = &$G_SHOP->DBCA->stmt_query($db_sql);
                $count=0;
                if ($temp_array){
                    foreach ($temp_array as &$item) {
                        $count=$item->nuber;
                    }
                }
                if($count>0){
                    $G_SHOP->DBCA->commit();
                    return array( 'code' => 800, 'message' => '您今天已经秒杀成功了一个蛋糕</br>不能再次秒杀，请明天再来' );
                }

                $activitySpike->spikeDate =$arg_array['spikeDate'];
                if($G_SHOP->DBCA->fetch($activitySpike))
                {
                    if(date('Y-m-d H:i:s')<date('Y-m-d 15:00:00')){ //测试数据
                        $G_SHOP->DBCA->commit();
                        return array( 'code' => 600, 'message' => '秒杀未开始，秒杀时间为今天15:00' );
                    }
                    //修改秒杀预约信息
                    $activitySpike->isSpike = $arg_array['isSpike'];
                    $activitySpike->spikeTime =$arg_array['spikeTime'];
                    $activitySpike->sku = $arg_array['sku'];
                }else{
                    $G_SHOP->DBCA->commit();
                    if(date('Y-m-d H:i:s')>date('Y-m-d 15:00:00')&&date('Y-m-d H:i:s')<date('Y-m-d 16:00:00'))
                        return array( 'code' => 600, 'message' => '您还没有预约，预约后才可秒杀</br>下场预约开始时间为：今天16:00' );
                    else
                        return array( 'code' => 600, 'message' => '您还没有预约，预约后才可秒杀</br>秒杀时间为今天15:00' );
                }
                $G_SHOP->DBCA->save($activitySpike) ;
                $G_SHOP->DBCA->commit();

                return array( 'code' => 500, 'message' => '秒杀成功' );
            }

        } catch (Exception $e) {

            $G_SHOP->DBCA->rollBack();

            if ($e->getCode() > 0)
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            else {
                error_log($e->getMessage());
                return array( 'code' => 700, 'message' => '系统错误' );
            }
        }
    }

    /**
     * 保存提交订单日志
     * @param array $arg_array 参数数组
     * @return null|array
     */
    public function saveLog( $arg_array )
    {
        global $G_SHOP;

        try
        {
            //mod by allen.qiang  万圣节秒杀调整 start
               /* $wsjDate=$this->getWeekSpikeDate(date('w'),2);

                if(date("Y-m-d")!=$wsjDate)
                {
                    return array( 'code' => 700, 'message' => '秒杀尚未开始，请耐心等待</br>秒杀时间：每周四11:00 - 16:00' );
                }else if(date('Y-m-d H:i:s')>date('Y-m-d 11:00:00')&&date('Y-m-d H:i:s')<=date('Y-m-d 16:00:00'))
                {*/
            if(date('Y-m-d H:i:s')>=date('Y-m-d 15:00:00')&&date('Y-m-d H:i:s')<=date('Y-m-d 16:00:00'))
            {
            //mod by allen.qiang  万圣节秒杀调整 end
                $G_SHOP->DBCA->beginTransaction();

                $activityLog = new entity('activity_log');
                $activityLog->creator = $arg_array['creator'];
                $activityLog->pcustID = $arg_array['pcustID'];
                $activityLog->sku = $arg_array['sku'];

                $G_SHOP->DBCA->save($activityLog) ;
                $G_SHOP->DBCA->commit();

                $sj=date('Y-m-d H:i:s',strtotime(date('Y-m-d H:i:s'))-300);
                //判断未下单但已经秒杀过的用户是否还在5分钟的提交订单时间内
                $user_sql = "SELECT COUNT(*) AS item_count FROM activity_spike WHERE spikeDate='".date('Y-m-d')."' AND pcustID='".$arg_array['pcustID']."' AND sku='".$arg_array['sku']."' AND codeState=0 AND isSpike=1 AND spikeTime>'".$sj."'";
                $temp_user_array = &$G_SHOP->DBCA->stmt_query($user_sql);
                $user_count=$temp_user_array[0]->item_count;
                if($user_count>0){ //还在5分钟的提交订单时间内
                    $activitySpike = new entity('activity_spike');
                    $activitySpike->pcustID = $arg_array['pcustID'];
                    $activitySpike->spikeDate =date('Y-m-d');
                    $activitySpike->sku = $arg_array['sku'];
                    if($G_SHOP->DBCA->fetch($activitySpike))
                    {
                        $db_sql = "SELECT COUNT(*) AS item_count FROM activity_spike WHERE spikeDate='".date('Y-m-d')."' AND pcustID='".$arg_array['pcustID']."' AND codeState<>0 ";
                        $temp_array = &$G_SHOP->DBCA->stmt_query($db_sql);
                        $count = $temp_array[0]->item_count;
                        if($count>0){
                            //mod by allen.qiang  万圣节秒杀调整 start
                                //return array( 'code' => 800, 'message' => '您今天已经成功秒杀了万圣节小鬼</br>不能再次秒杀，请下周四再来' );
                            return array( 'code' => 800, 'message' => '您今天已经成功秒杀了万圣节小鬼</br>不能再次秒杀，请明天再来' );
                            //mod by allen.qiang  万圣节秒杀调整 end
                        }else{
                            $search_sql = "SELECT COUNT(*) AS item_count FROM activity_spike WHERE spikeDate='".date('Y-m-d')."' AND sku='".$arg_array['sku']."' AND codeState<>0 ";
                            $temp_item_array = &$G_SHOP->DBCA->stmt_query($search_sql);
                            if ($temp_item_array){
                                $sum = $temp_item_array[0]->item_count;
                                if($sum>1){
                                    return array( 'code' => 400, 'message' => '秒杀已被抢光，等下次机会吧' );
                                }else{
                                    return array( 'code' => 500, 'message' => '添加日志成功' );
                                }
                            }else{
                                return array( 'code' => 500, 'message' => '添加日志成功' );
                            }
                        }
                    }else{
                        // $G_SHOP->DBCA->commit();
                        return array( 'code' => 600, 'message' => '您还没有预约，预约后才可秒杀' );
                    }
                }else{
                    return array( 'code' => 900, 'message' => '订单超时,秒杀失败' );
                }

            }else{
                return array( 'code' => 900, 'message' => '秒杀已结束' );
            }


        } catch (Exception $e) {

            $G_SHOP->DBCA->rollBack();

            if ($e->getCode() > 0)
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            else {
                error_log($e->getMessage());
                return array( 'code' => 700, 'message' => '系统错误' );
            }
        }
    }

    /**
     * 订单成功录入订单号
     * @param array $arg_array 参数数组
     * @return null|array
     */
    public function upSpike( $arg_array )
    {
        global $G_SHOP;

        try
        {
            $G_SHOP->DBCA->beginTransaction();

            $activitySpike = new entity('activity_spike');
            $activitySpike->pcustID = $arg_array['pcustID'];
            $activitySpike->spikeDate =$arg_array['spikeDate'];
            if($G_SHOP->DBCA->fetch($activitySpike))
            {
                //修改秒杀预约订单信息
                $activitySpike->bill_code = $arg_array['bill_code'];
                $activitySpike->codeState = $arg_array['codeState'];
            }
            $G_SHOP->DBCA->save($activitySpike) ;
            $G_SHOP->DBCA->commit();
        } catch (Exception $e) {

            $G_SHOP->DBCA->rollBack();

            if ($e->getCode() > 0)
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            else {
                error_log($e->getMessage());
                return array( 'code' => 700, 'message' => '系统错误' );
            }
        }
    }


    /**
     * 查询用户是否已预约万圣节活动 0：未预约，未在活动时间内购买蛋糕；1：未预约，已在活动时间内购买蛋糕；2：已预约;3:已秒杀；
     * @return null|array
     */
    public function searchWsjSpike() {
        global $G_SHOP;

        $pcustID=$G_SHOP->currentPCustID;

        $activitySpike = new entity('activity_spike');
        $activitySpike->pcustID = $pcustID;
        //mod by allen.qiang  万圣节秒杀调整 start
            //$activitySpike->spikeDate =$this->getWeekSpikeDate(date("w"),2);
        $activitySpike->spikeDate =date('Y-m-d');
        //mod by allen.qiang  万圣节秒杀调整 end
        if($G_SHOP->DBCA->fetch($activitySpike))
        {
            $activitySpike->isSpike = 1;
            $activitySpike->codeState = 1;
            if($G_SHOP->DBCA->fetch($activitySpike))
            {
                return 3;
            }else{
                return 2;
            }
        }else{
            //sql字符串
            $sql2 =  "SELECT COUNT(*) AS item_count FROM bill_master WHERE pcustID=? AND billType IN (1,4,8) AND  bill_status<>10 AND bill_card_money=0  AND bill_money<>0 AND createTime>? AND createTime<?";

            //参数类型字符串
            $params_type2 = '';

            //参数值数组

            $params_array2 = array();
            $params_type2 .= 's';
            $params_array2[] =$pcustID;
            $params_type2 .= 's';
            $params_array2[] ="2014-10-17 10:00:00";
            $params_type2 .= 's';
            $params_array2[] ="2014-11-06 15:00:00";

            $temp_item_array2 = &$G_SHOP->DBCA->stmt_query($sql2,$params_type2,$params_array2);
            if (!$temp_item_array2)
                return null;
            $item_count2 = $temp_item_array2[0]->item_count;
            if ($item_count2 > 0) {
                return 1;
            }else{
                return 0;
            }
        }

    }

    /**
     * 查询万圣节秒杀活动参与人数详情
     * @return null|array
     */
    public function searchWsjSpikeDetail() {
        global $G_SHOP;
        $pcustID=$G_SHOP->currentPCustID;
        $s_sql="SELECT * FROM `activity_goods` WHERE isDisable=0 ORDER BY orderID";
        $temp_array = &$G_SHOP->DBCA->stmt_query($s_sql);
        if (!$temp_array)
            return null;
        $date=$this->getWsjSpikeDate(date('w'));
        $date1=$date[0];
        $date2=$date[1];
        $statusDate=date('Y-m-d',strtotime("$date1 +1 day"));
        $endDate=date('Y-m-d',strtotime("$date2 -1 day"));
        $isStatus=0; //预约时间状态：0:预约时间已结束；1:预约中
        if($statusDate." 10:00:00"<=date('Y-m-d H:i:s') && date('Y-m-d H:i:s')<=$endDate." 22:00:00"){
            $isStatus=1;
        }
        $customer_array = array();

        foreach ($temp_array as &$items) {
            //查询用户是否已预约万圣节活动 0：未预约，未在活动时间内购买蛋糕；1：未预约，已在活动时间内购买蛋糕；2：已预约；3:已秒杀；4：秒杀结束；5：已有秒杀资格
            $isSipke=$this->searchWsjSpike();
            $sj=date('Y-m-d H:i:s',strtotime(date('Y-m-d H:i:s'))-300);
            //获取已经下单的用户或未下单但已经秒杀过且在5分钟的提交订单时间内的用户数量
            $search_sql = "SELECT COUNT(*) AS item_count FROM activity_spike WHERE spikeDate='".date('Y-m-d')."' AND sku='".$items->sku."' AND (codeState<>0 OR (codeState=0 AND isSpike=1 AND spikeTime>'".$sj."'))";
            $temp_item_array = &$G_SHOP->DBCA->stmt_query($search_sql);
            if (!$temp_item_array)
                return null;
            //得到实际秒杀数量
            $item_count = $temp_item_array[0]->item_count;
            $sum=10-$item_count*2;
            if($isSipke==2){
                $btnName="剩余".$sum."组";
            }else if($isSipke==3){
                $btnName="已秒杀成功";
            }else{
                $btnName="需先预约";
            }

            if($sum==0||date('Y-m-d H:i:s')>$this->getWeekSpikeDate(date("w"),2)." 16:00:00"){
                $sum=0;
                if($isSipke!=3&&$isSipke==2){
                    $isSipke=4;
                    $btnName="秒杀已被抢光";
                }
            }
            //获取未下单但已经秒杀过的用户是否还在5分钟的提交订单时间内
            $user_sql = "SELECT COUNT(*) AS item_count FROM activity_spike WHERE spikeDate='".date('Y-m-d')."' AND pcustID='".$pcustID."' AND sku='".$items->sku."' AND codeState=0 AND isSpike=1 AND spikeTime>'".$sj."'";
            $temp_user_array = &$G_SHOP->DBCA->stmt_query($user_sql);
            $user_count=$temp_user_array[0]->item_count;
            if($user_count>0&&$isSipke!=4){
                $isSipke=5;
                $btnName="已有秒杀资格";
            }
            //用户信息数组
            $customer_array[]  = array(
                'nuber'	    => 	$sum,
                'buttonName'	    => 	$btnName,
                'product_code'   => 	$items->sku,
                'product_src'   => 	$items->src,
                'product_postID_SH'   => 	$items->postID_SH,
                'product_postID_HZ'   => 	$items->postID_HZ,
                'product_goodsName'   => 	$items->goodsName,
                'product_pounds'   => 	$items->pounds,
                'spikeStatus' =>$isSipke,
                'yuyueStatus'=>$isStatus
            );
        }
        return $customer_array;

    }


    /**
     * 保存/修改 万圣节 预约/秒杀 表信息
     * @param array $arg_array 参数数组
     * @return null|array
     */
    public function saveWsjSpike( $arg_array )
    {
        global $G_SHOP;

        try {

            $G_SHOP->DBCA->beginTransaction();

            $activitySpike = new entity('activity_spike');
            $activitySpike->pcustID = $arg_array['pcustID'];

            $operFlg=$arg_array['operFlg'];
            if ($operFlg == 6) {//预约

                $date=$this->getWsjSpikeDate(date('w'));
                $date1=$date[0];
                $date2=$date[1];
                $statusDate=date('Y-m-d',strtotime("$date1 +1 day"));
                $endDate=date('Y-m-d',strtotime("$date2 -1 day"));

                if($statusDate." 10:00:00"<=date('Y-m-d H:i:s') && date('Y-m-d H:i:s')<=$endDate." 22:00:00"){
                    //查询秒杀预约信息
                    $activitySpike->spikeDate =$arg_array['spikeDate'];
                    if($G_SHOP->DBCA->fetch($activitySpike))
                    {
                        $G_SHOP->DBCA->commit();
                        return array( 'code' => 200, 'message' => '<label style="font-weight: bold;">您已预约</label> </br>您已经预约成功！可以参与秒杀啦！</br>秒杀时间：每周四11:00 - 16:00' );
                    }

                    $activitySpike->creator = $arg_array['creator'];
                    $activitySpike->appointmentTime = $arg_array['appointmentTime'];
                    $activitySpike->isSpike = $arg_array['isSpike'];

                    //保存秒杀预约信息
                    $G_SHOP->DBCA->save( $activitySpike ) ;

                    //保存秒杀活动信息
                    $number=1;
                    $activityEvents=new entity('activity_events');
                    $activityEvents->eventsID = $this->eventsID;

                    if( !$G_SHOP->DBCA->fetch($activityEvents) ) {//新增

                        $activityEvents->eventsName =  $this->eventsName;
                        $activityEvents->beginTime =  $this->beginTime;
                        $activityEvents->endTime =  $this->endTime;
                        $activityEvents->sourceID = $this->billPromotion;
                        $activityEvents->number += $number;
                    }else{
                        $activityEvents->number += $number;//修改参与人数
                    }
                    $G_SHOP->DBCA->save($activityEvents) ;
                    $G_SHOP->DBCA->commit();

                    return array( 'code' => 200, 'message' => '<label style="font-weight: bold;">预约成功</label> </br>恭喜您预约成功！您可以参与秒杀啦！</br>秒杀时间：每周四11:00 - 16:00' );

                }else{
                    $G_SHOP->DBCA->commit();
                    return array( 'code' => 300, 'message' => '<label style="font-weight: bold;">预约已结束</label> </br>下次预约开始时间为：本周五早上10:00 ，请注意及时预约' );
                }

            } else if($operFlg == 7){//立即秒杀

                $sj=date('Y-m-d H:i:s',strtotime(date('Y-m-d H:i:s'))-300);
                //获取已经下单的用户或未下单但已经秒杀过且在5分钟的提交订单时间内的用户数量
                $search_sql = "SELECT COUNT(*) AS item_count FROM activity_spike WHERE spikeDate='".date('Y-m-d')."' AND sku='".$arg_array['sku']."' AND (codeState<>0 OR (codeState=0 AND isSpike=1 AND spikeTime>'".$sj."'))";
                $temp_item_array = &$G_SHOP->DBCA->stmt_query($search_sql);
                //获取未下单但已经秒杀过的用户是否还在5分钟的提交订单时间内
                $user_sql = "SELECT COUNT(*) AS item_count FROM activity_spike WHERE spikeDate='".date('Y-m-d')."' AND pcustID='".$arg_array['pcustID']."' AND sku='".$arg_array['sku']."' AND codeState=0 AND isSpike=1 AND spikeTime>'".$sj."'";
                $temp_user_array = &$G_SHOP->DBCA->stmt_query($user_sql);
                $user_count=$temp_user_array[0]->item_count;
                //得到秒杀资格数量(未下单)
                $item_count = $temp_item_array[0]->item_count;
                if($item_count>4 && $user_count==0){
                    $G_SHOP->DBCA->commit();
                    return array( 'code' => 700, 'message' => '秒杀已被抢光，等下次机会吧' );
                }
                $db_sql = "SELECT COUNT(*) AS item_count FROM activity_spike WHERE spikeDate='".date('Y-m-d')."' AND pcustID='".$arg_array['pcustID']."' AND sku='".$arg_array['sku']."' AND codeState<>0 ";
                $temp_array = &$G_SHOP->DBCA->stmt_query($db_sql);
                $count= $temp_array[0]->item_count;//已下单数量
                if($count>0){
                    $G_SHOP->DBCA->commit();
                    return array( 'code' => 800, 'message' => '您今天已经成功秒杀了万圣节小鬼</br>不能再次秒杀，请下周四再来' );
                }

                $activitySpike->spikeDate =$arg_array['spikeDate'];
                if($G_SHOP->DBCA->fetch($activitySpike))
                {

                    $wsjDate=$this->getWeekSpikeDate(date('w'),2);
                    if(date("Y-m-d")!=$wsjDate || date('Y-m-d H:i:s')<date('Y-m-d 11:00:00') || date('Y-m-d H:i:s')>date('Y-m-d 16:00:00'))
                    {
                        $G_SHOP->DBCA->commit();
                        return array( 'code' => 600, 'message' => '秒杀尚未开始，请耐心等待</br>秒杀时间：每周四11:00 - 16:00' );
                    }
                    //修改秒杀预约信息
                    $activitySpike->isSpike = $arg_array['isSpike'];
                    $activitySpike->spikeTime =$arg_array['spikeTime'];
                    $activitySpike->sku = $arg_array['sku'];
                }
                $G_SHOP->DBCA->save($activitySpike) ;
                $G_SHOP->DBCA->commit();

                return array( 'code' => 500, 'message' => '秒杀成功' );
            }

        } catch (Exception $e) {

            $G_SHOP->DBCA->rollBack();

            if ($e->getCode() > 0)
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            else {
                error_log($e->getMessage());
                return array( 'code' => 700, 'message' => '系统错误' );
            }
        }
    }

    /**
     * 根据当前日期判断活动区间
     * @param int $week 星期几
     * @return date
     */
    public function getWsjSpikeDate($week){

        $statusDate="";
        $endDate="";
        switch($week){
            case 1:
                $statusDate=date('Y-m-d',strtotime('-4 day'));
                $endDate=date('Y-m-d',strtotime('+3 day'));
                break;
            case 2:
                $statusDate=date('Y-m-d',strtotime('-5 day'));
                $endDate=date('Y-m-d',strtotime('+2 day'));
                break;
            case 3:
                $statusDate=date('Y-m-d',strtotime('-6 day'));
                $endDate=date('Y-m-d',strtotime('+1 day'));
                break;
            case 4:
                $statusDate=date('Y-m-d');
                $endDate=date('Y-m-d');
                break;
            case 5:
                $statusDate=date('Y-m-d',strtotime('-1 day'));
                $endDate=date('Y-m-d',strtotime('+6 day'));
                break;
            case 6:
                $statusDate=date('Y-m-d',strtotime('-2 day'));
                $endDate=date('Y-m-d',strtotime('+5 day'));
                break;
            default:
                $statusDate=date('Y-m-d',strtotime('-3 day'));
                $endDate=date('Y-m-d',strtotime('+4 day'));
                break;
        }

        $item_array[] = array();
        $item_array[0]=$statusDate;
        $item_array[1]=$endDate;
       return $item_array;
    }

    /**
     * 根据当前时间得到万圣节活动的时间
     * @param int $week 星期几
     * @param int $type 参数类型
     * @return date
     */
    public function getWeekSpikeDate($week,$type){
        switch($week){
            case 1:
                $WeekDate=date('Y-m-d',strtotime('+3 day'));
                return $WeekDate;
                break;
            case 2:
                $WeekDate=date('Y-m-d',strtotime('+2 day'));
                return $WeekDate;
                break;
            case 3:
                $WeekDate=date('Y-m-d',strtotime('+1 day'));
                return $WeekDate;
                break;
            case 4:
                $WeekDate=date('Y-m-d');
                if($type==1 && date('Y-m-d 16:00:00')<date("Y-m-d H:i:s")){
                    $WeekDate=date('Y-m-d',strtotime('+7 day'));
                }
                return $WeekDate;
                break;
            case 5:
                $WeekDate=date('Y-m-d',strtotime('+6 day'));
                return $WeekDate;
                break;
            case 6:
                $WeekDate=date('Y-m-d',strtotime('+5 day'));
                return $WeekDate;
                break;
            default:
                $WeekDate=date('Y-m-d',strtotime('+4 day'));
                return $WeekDate;
                break;
        }
    }

    /**
     * 万圣节 秒杀
     * @param array $arg_array 参数数组
     * @return null|array
     * @author  20141024 allen.qiang <allen.qiang@fistforward.com>
     */
    public function WsjmsSpike( $arg_array )
    {
        global $G_SHOP;

        try {
            if(date('Y-m-d H:i:s')<date('Y-m-d 15:00:00') || date('Y-m-d H:i:s')>date('Y-m-d 16:00:00'))
            {
                return array( 'code' => 600, 'message' => '秒杀尚未开始，请耐心等待</br>秒杀时间：每天15:00 - 16:00' );
            }else{
                $G_SHOP->DBCA->beginTransaction();

                $sj=date('Y-m-d H:i:s',strtotime(date('Y-m-d H:i:s'))-300);
                //获取已经下单的用户或未下单但已经秒杀过且在5分钟的提交订单时间内的用户数量
                $search_sql = "SELECT COUNT(*) AS item_count FROM activity_spike WHERE spikeDate='".date('Y-m-d')."' AND sku='".$arg_array['sku']."' AND (codeState<>0 OR (codeState=0 AND isSpike=1 AND spikeTime>'".$sj."'))";
                $temp_item_array = &$G_SHOP->DBCA->stmt_query($search_sql);
                //获取未下单但已经秒杀过的用户是否还在5分钟的提交订单时间内
                $user_sql = "SELECT COUNT(*) AS item_count FROM activity_spike WHERE spikeDate='".date('Y-m-d')."' AND pcustID='".$arg_array['pcustID']."' AND sku='".$arg_array['sku']."' AND codeState=0 AND isSpike=1 AND spikeTime>'".$sj."'";
                $temp_user_array = &$G_SHOP->DBCA->stmt_query($user_sql);
                $user_count=$temp_user_array[0]->item_count;//用户是否有秒杀资格
                //得到库存数量(未下单)
                $item_count = $temp_item_array[0]->item_count;
                if($item_count>1 && $user_count==0){
                    $G_SHOP->DBCA->commit();
                    return array( 'code' => 700, 'message' => '秒杀已被抢光，等下次机会吧<br /> 每天下午15:00准点秒杀' );
                }
                $db_sql = "SELECT COUNT(*) AS item_count FROM activity_spike WHERE spikeDate='".date('Y-m-d')."' AND pcustID='".$arg_array['pcustID']."' AND sku='".$arg_array['sku']."' AND codeState<>0 ";
                $temp_array = &$G_SHOP->DBCA->stmt_query($db_sql);
                $count= $temp_array[0]->item_count;//用户已秒杀数量
                if($count>0){
                    $G_SHOP->DBCA->commit();
                    return array( 'code' => 800, 'message' => '您今天已经成功秒杀了万圣节小鬼</br>不能再次秒杀，请明天再来' );
                }

                //保存秒杀预约信息
                $activitySpike = new entity('activity_spike');
                $activitySpike->pcustID = $arg_array['pcustID'];
                $activitySpike->spikeDate =$arg_array['spikeDate'];
                if(!$G_SHOP->DBCA->fetch($activitySpike))
                {
                    $activitySpike->creator = $arg_array['creator'];
                    $activitySpike->appointmentTime = $arg_array['appointmentTime'];
                    $activitySpike->isSpike = $arg_array['isSpike'];
                    $activitySpike->spikeTime =$arg_array['spikeTime'];
                    $activitySpike->sku = $arg_array['sku'];
                }else if($user_count==0){
                    $activitySpike->isSpike = $arg_array['isSpike'];
                    $activitySpike->spikeTime =$arg_array['spikeTime'];
                    $activitySpike->sku = $arg_array['sku'];
                }

                $G_SHOP->DBCA->save($activitySpike) ;
                $G_SHOP->DBCA->commit();

                return array( 'code' => 500, 'message' => '秒杀成功' );
            }

        } catch (Exception $e) {

            $G_SHOP->DBCA->rollBack();

            if ($e->getCode() > 0)
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            else {
                error_log($e->getMessage());
                return array( 'code' => 700, 'message' => '系统错误' );
            }
        }
    }

    /**
     * 查询万圣节秒杀活动详情
     * @return null|array
     * @author  20141024 allen.qiang <allen.qiang@fistforward.com>
     */
    public function WsjmsSpikeDetail() {
        global $G_SHOP;
        $pcustID=$G_SHOP->currentPCustID;
        $s_sql="SELECT * FROM `activity_goods` WHERE isDisable=0 ORDER BY orderID";
        $temp_array = &$G_SHOP->DBCA->stmt_query($s_sql);
        if (!$temp_array)
            return null;

        $customer_array = array();
        foreach ($temp_array as &$items) {
            //查询用户是否已预约万圣节活动 0：未预约，未在活动时间内购买蛋糕；1：未预约，已在活动时间内购买蛋糕；3:已秒杀；4：秒杀结束；5：已有秒杀资格
            $isSipke=$this->searchWsjSpike();
            $sj=date('Y-m-d H:i:s',strtotime(date('Y-m-d H:i:s'))-300);
            //获取已经下单的用户或未下单但已经秒杀过且在5分钟的提交订单时间内的用户数量
            $search_sql = "SELECT COUNT(*) AS item_count FROM activity_spike WHERE spikeDate='".date('Y-m-d')."' AND sku='".$items->sku."' AND (codeState<>0 OR (codeState=0 AND isSpike=1 AND spikeTime>'".$sj."'))";
            $temp_item_array = &$G_SHOP->DBCA->stmt_query($search_sql);
            if (!$temp_item_array)
                return null;
            //得到实际秒杀数量
            $item_count = $temp_item_array[0]->item_count;
            $sum=6-$item_count*3; //假数据

            if(date('Y-m-d H:i:s')<date('Y-m-d 15:00:00')){
                if($isSipke==0)
                    $btnName="（请先购买蛋糕）";
                else
                    $btnName="（秒杀未开始）";
            }else if($isSipke==3){
                $btnName="（已秒杀成功）";
            }else if(date('Y-m-d H:i:s')>date('Y-m-d 16:00:00')){
                $sum=0;
                if($isSipke==0)
                    $btnName="（请先购买蛋糕）";
                else{
                    $isSipke=4;
                    $btnName="（秒杀已结束）";
                }

            }else{
                //获取未下单但已经秒杀过的用户是否还在5分钟的提交订单时间内
                $user_sql = "SELECT COUNT(*) AS item_count FROM activity_spike WHERE spikeDate='".date('Y-m-d')."' AND pcustID='".$pcustID."' AND sku='".$items->sku."' AND codeState=0 AND isSpike=1 AND spikeTime>'".$sj."'";
                $temp_user_array = &$G_SHOP->DBCA->stmt_query($user_sql);
                $user_count=$temp_user_array[0]->item_count;
                if($user_count>0){
                    $isSipke=5;
                    $btnName="（已有秒杀资格）";
                }else if($sum==0){
                    if($isSipke==0)
                        $btnName="（请先购买蛋糕）";
                    else
                        $btnName="（秒杀已抢光）";
                }else{
                    if($isSipke==2)
                        $isSipke=1;
                    if($isSipke==0)
                        $btnName="（请先购买蛋糕）";
                    else
                        $btnName="（剩余".$sum."组）";
                }
            }

            //用户信息数组
            $customer_array[]  = array(
                'nuber'	    => 	$sum,
                'buttonName'	    => 	$btnName,
                'product_code'   => 	$items->sku,
                'product_src'   => 	$items->src,
                'product_postID_SH'   => 	$items->postID_SH,
                'product_postID_HZ'   => 	$items->postID_HZ,
                'product_goodsName'   => 	$items->goodsName,
                'product_pounds'   => 	$items->pounds,
                'spikeStatus' =>$isSipke
            );
        }
        return $customer_array;

    }

    /**
     * 判断农业银行信用卡五折购的活动时间
     * @return true|false
     * @author  20141029 allen.qiang <allen.qiang@fistforward.com>
     */
    public function nh_xyk_isDate(){
        if((date('w')==4 || date('w')==5 || date('w')==6) && date('Y-m-d H:i:s')<=date('Y-12-15 23:00:00')){
            return true;//array( 'code' => 200, 'message' => '活动时间内' );
        }else{
            return false; //array( 'code' => 400, 'message' => '不在活动时间内' );
        }
    }

    /**
     * 记录页面上【申请农行信用卡】按钮的点击次数
     * @return null|array
     * @author  20141029 allen.qiang <allen.qiang@fistforward.com>
     */
    public function nh_xyk_log(){
        global $G_SHOP;

        try {
            $G_SHOP->DBCA->beginTransaction();

            $activityLog = new entity('activity_log');
            $activityLog->creator = $G_SHOP->currentCustomerID==""?$this->getIP():$G_SHOP->currentCustomerID;
            $activityLog->pcustID = $G_SHOP->currentPCustID;
            $activityLog->sku = "nh_xyk";

            $G_SHOP->DBCA->save($activityLog) ;
            $G_SHOP->DBCA->commit();
            return array( 'code' => 200, 'message' => '记录成功' );
        } catch (Exception $e) {

            $G_SHOP->DBCA->rollBack();
            if ($e->getCode() > 0)
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            else {
                error_log($e->getMessage());
                return array( 'code' => 700, 'message' => '系统错误' );
            }
       }
    }

    /**
     * 查询农业银行信用卡五折购蛋糕数量
     * @return null|$item_count
     * @author  20141029 allen.qiang <allen.qiang@fistforward.com>
     */
    public function nh_xyk_num(){
        global $G_SHOP;

        $search_sql = "
        SELECT COUNT(*)AS item_count
          FROM bill_goods t1,
            (SELECT bill_no FROM bill_master
              WHERE billPromotion = ".$this->billPromotion_ny_xyk." ) t2
          WHERE t1.bill_no = t2.bill_no
          AND t1.goods_spec = '1磅'";
        $temp_item_array = &$G_SHOP->DBCA->stmt_query($search_sql);
        if (!$temp_item_array)
            return null;
        //得到实际蛋糕数量
        $item_count =3499-$temp_item_array[0]->item_count;
        if($item_count<0)
            $item_count=0;
        return $item_count;
    }

    /**
     * 查询农业银行信用卡五折购蛋糕数量
     * @return null|$item_count
     * @author  20141029 allen.qiang <allen.qiang@fistforward.com>
     */
    public function nh_xyk_num400(){
        global $G_SHOP;
        quanli_require('module/base/activity/activityConfig.class.php');
        //实例化配置类
        $activity_config = new activityConfig('nh_xyk'); //农行信用卡五折购活动配置
        $config_array = $activity_config->config;

        $search_sql = "
        SELECT COUNT(*)AS item_count
          FROM bill_goods t1,
            (SELECT bill_no FROM bill_master
              WHERE billPromotion = ".$this->billPromotion_ny_xyk." ) t2
          WHERE t1.bill_no = t2.bill_no
          AND t1.goods_spec = '1磅'";
        $temp_item_array = &$G_SHOP->DBCA->stmt_query($search_sql);
        if (!$temp_item_array)
            return null;
        //得到实际蛋糕数量
        $item_count =$config_array["goods_count"]-$temp_item_array[0]->item_count;
        if($item_count<0)
            $item_count=0;
        return $item_count;
    }


   /**
    * 查询IP
    * @return $realip
    * @author  20141029 allen.qiang <allen.qiang@fistforward.com>
    */
    public function getIP()
    {
        static $realip;
        if (isset($_SERVER)){
            if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])){
                $realip = $_SERVER["HTTP_X_FORWARDED_FOR"];
            } else if (isset($_SERVER["HTTP_CLIENT_IP"])) {
                $realip = $_SERVER["HTTP_CLIENT_IP"];
            } else {
                $realip = $_SERVER["REMOTE_ADDR"];
            }
        } else {
            if (getenv("HTTP_X_FORWARDED_FOR")){
                $realip = getenv("HTTP_X_FORWARDED_FOR");
            } else if (getenv("HTTP_CLIENT_IP")) {
                $realip = getenv("HTTP_CLIENT_IP");
            } else {
                $realip = getenv("REMOTE_ADDR");
            }
        }
        return $realip;
    }


}